package com.huayu.languo.common.framework;

import com.huayu.languo.common.constant.AppConstants;
import com.huayu.languo.common.util.AppProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 跨域过滤器
 */
@Component
public class CorsFilter implements Filter {

    /**
     * 是否需要过滤 跨域域名
     */
    private static boolean needFilterOrigin = Boolean.parseBoolean(AppProperties.getSysEnvOrProp(AppConstants.NEED_FILTER_ORIGIN, AppConstants.FALSE_STR));

    /**
     * 允许的跨域的 域名
     */
    private static List<String> allowOrigin = Arrays.asList(AppProperties.getSysEnvOrProp(AppConstants.NEED_FILTER_ORIGIN, AppConstants.DEFAULT_STR_VAL));

    /**
     * 允许的跨域请求头
     */
    private static String allowHeaders = "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, Cookie";

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if (needFilterOrigin) {
            String origin = request.getHeader("Origin");
            if (StringUtils.isNotEmpty(origin) && allowOrigin.contains(origin)) {
                response.addHeader("Access-Control-Allow-Origin", origin);
            }
        } else {
            response.addHeader("Access-Control-Allow-Origin", "*");
        }
        String requestHeaders = request.getHeader("Access-Control-Request-Headers");
        String theAllowHeaders = allowHeaders;
        if (StringUtils.isNotEmpty(requestHeaders)) {
            theAllowHeaders = allowHeaders.concat(", ").concat(requestHeaders);
        }
        response.addHeader("Access-Control-Allow-Headers", theAllowHeaders);
        response.addHeader("Access-Control-Expose-Headers", theAllowHeaders);
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
        // 最大有效缓存时间5分钟
        response.addHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // do noting
    }

    @Override
    public void destroy() {
        // do noting
    }
}
